package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringReader;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXB;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.LogosticsInfo;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillBoxPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.exception.ErrorCode;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.LogosticsInfoDao;
import com.topisv.tms.rest.qimen.qmentity.SenderInfo;
import com.topisv.tms.rest.qimen.qmentity.request.returninstoragecreate.ReturnInstorageCreate;
import com.topisv.tms.rest.qimen.qmentity.request.returninstoragecreate.ReturnOrder;
import com.topisv.tms.rest.qimen.qmentity.request.returninstoragecreate.ReturnOrderItem;
import com.topisv.tms.rest.qimen.qmentity.response.QMReponse;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.qmentity.response.returninstoragecreate.ReturnInstorageCreateResult;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.rest.qimen.util.validator.ValidatorUtil;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.stock.preinstorage.PreInstorageService;
import com.topisv.tms.utils.vo.PreInstorageVo;
@Component
@Transactional(readOnly=true)
public class ReturnInstorageCreateService {

	private static final Logger logger = LoggerFactory.getLogger(ReturnInstorageCreateService.class);

	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	@Autowired
	private LogosticsInfoDao logosticsInfoDao;
	@Autowired
	private PreInstorageService preInstorageService;
	@Autowired
	private EdiOrderService ediOrderService;
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public ResponseParams execute(RequestParams params) throws PaiUException {
		//返回请求参数
		ResponseParams response = new ResponseParams();
		ReturnInstorageCreateResult result = new ReturnInstorageCreateResult();
		try {
			logger.info("退货入库");
			String stringXml = params.getRequestXml();
//			Map<String, String> map =  params.getParams();
//			String code = map.get(RequestParamsParse.CUSTOMERID);
			ReturnInstorageCreate instoragebillcreate = JAXB.unmarshal(new StringReader(stringXml), ReturnInstorageCreate.class);
			
            // 报文校验
            String reqValidatorMsg = ValidatorUtil.qmXmlValidator(instoragebillcreate);
            if (!ValidatorUtil.SUCCESS_CODE.equals(reqValidatorMsg)) {
                response.setResponseXml(reqValidatorMsg.toString());
                return response;
            }
			
			
			ReturnOrder order = instoragebillcreate.getReturnOrder();
			SenderInfo senderInfo = order.getSenderInfo();
			
			
			//设置InstorageBillPre数据
			InstorageBillPre billPre = new InstorageBillPre();
			billPre.setOrderStatus("1");	//改成已发货状态
			billPre.setCustomerOrderNo(order.getReturnOrderCode());
			billPre.setCustomerCode(instoragebillcreate.getItem().get(0).getOwnerCode());
			billPre.setInwarehouseCode(order.getWarehouseCode());
			billPre.setOrderFlag(order.getOrderFlag());
			if(StringUtils.isEmpty(order.getSourceOrderCode())){
				EdiOrder ediOrder = ediOrderService.findByOrdeno(order.getPreDeliveryOrderId());
				if(ediOrder!=null){
					order.setSourceOrderCode(ediOrder.getFromno());
				}
			}
			billPre.setOldCusOrderNo(order.getSourceOrderCode());
			billPre.setLogisticsCode(order.getLogisticsCode());
			billPre.setLogisticsName(order.getLogisticsName());
			billPre.setExpressNo(order.getExpressCode());
			billPre.setReturnReason(order.getReturnReason());
			billPre.setRemark(order.getRemark());
			
			//设置发件人的数据
			LogosticsInfo logosticsInfo = new LogosticsInfo();
			logosticsInfo.setExpressNo(billPre.getExpressNo());
			logosticsInfo.setLogosticsInfo(billPre.getLogisticsCode());
			logosticsInfo.setSenderCompany(senderInfo.getCompany());
			logosticsInfo.setSenderName(senderInfo.getName());
			logosticsInfo.setSenderZipCode(senderInfo.getZipCode());
			logosticsInfo.setSenderTel(senderInfo.getTel());
			logosticsInfo.setSenderMobile(senderInfo.getMobile());
			logosticsInfo.setSenderEmail(senderInfo.getEmail());
			logosticsInfo.setSenderCountryCode(senderInfo.getCountryCode());
			logosticsInfo.setSenderProvince(senderInfo.getProvince());
			logosticsInfo.setSenderCity(senderInfo.getCity());
			logosticsInfo.setSenderArea(senderInfo.getArea());
			logosticsInfo.setSenderTown(senderInfo.getTown());
			logosticsInfo.setSenderDetailAddress(senderInfo.getDetailAddress());
			
			//设置一个虚拟箱位
			List<InstorageBillBoxPre> boxes = new ArrayList<InstorageBillBoxPre>();
			InstorageBillBoxPre box = new InstorageBillBoxPre();
			box.setBoxCode("QMBOX0001");
			boxes.add(box);
			
			//设置InstorageBillItemPre数据
			List<InstorageBillItemPre> itemPres = new ArrayList<InstorageBillItemPre>();
			for(ReturnOrderItem item : instoragebillcreate.getItem()){
				EdiGoodsSku goodsSku = ediGoodsSkuDao.findOne(Long.parseLong(item.getItemId()));
				if (goodsSku == null) {
					throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] { item.getItemId() });
				}
				
				if (goodsSku.getIsBatchMgmt().equals("1") && (item.getBatchCode() == null || item.getBatchCode().equals(""))){
                    throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "必须输入批次"});
                }
                
                if(goodsSku.getIsShelfLifeMgmt().equals("1")){
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    if(goodsSku.getShelfLife() == null || goodsSku.getShelfLife().equals(0)){
                        if((item.getProductDate() == null || item.getProductDate().equals("")) || 
                            (item.getExpireDate() == null || item.getExpireDate().equals(""))){
                            throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "未维护保质期，必须输入生产日期及过期日期"});
                        }else{
                            //验证生产日期和过期日期的日期格式
                            Date date = sdf2.parse(item.getProductDate());
                            date = sdf2.parse(item.getExpireDate());
                            if(date.before(new Date())){
                                throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "过期日期小于当天"}); 
                            }
                        }
                    }else{
                        if((item.getProductDate() == null || item.getProductDate().equals("")) && 
                            (item.getExpireDate() == null || item.getExpireDate().equals(""))){
                            throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "必须输入生产日期或过期日期"});
                        }else{
                            if(item.getExpireDate() == null || item.getExpireDate().equals("")){
                                Date date = sdf2.parse(item.getProductDate());
                                date = new Date(date.getTime() + (goodsSku.getShelfLife() * 60 * 60 * 1000));
                                if(date.before(new Date())){
                                    throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "过期日期小于当天"}); 
                                }
                                item.setExpireDate(sdf2.format(date));
                            }else{
                                Date date = sdf2.parse(item.getExpireDate());
                                if(date.before(new Date())){
                                    throw new PaiUException(ErrorCode.SKU_CONFIG_ERROR, new String[] {item.getItemCode() + "过期日期小于当天"}); 
                                }
                                date = new Date(date.getTime() - (goodsSku.getShelfLife() * 60 * 60 * 1000));
                                item.setProductDate(sdf2.format(date));
                            }
                        }
                    }
                }
				
				InstorageBillItemPre itemPre = new InstorageBillItemPre();
				itemPre.setLineNo(item.getOrderLineNo());
				itemPre.setSourceOrderCode(item.getSourceOrderCode());
				itemPre.setSubSourceOrderCode(item.getSubSourceOrderCode());
				itemPre.setSkuCode(goodsSku.getSku());
				itemPre.setItemId(goodsSku.getId().toString());
				itemPre.setBoxCode("QMBOX0001");
				itemPre.setInventoryType(item.getInventoryType());
				itemPre.setGoodsNum(item.getQuantity());
				itemPres.add(itemPre);
			}
			//封装到Vo
			PreInstorageVo preInstorageVo = new PreInstorageVo();
			preInstorageVo.setInstorageBillPre(billPre);
			preInstorageVo.setInstorageBillBoxPres(boxes);   
			preInstorageVo.setInstorageBillItemPres(itemPres);
			
//			String billtype = "";
//			if("THRK".equals(order.getOrderType())){
			String billtype = "returnOrder";
//			}
			InstorageBillPre instorageBillPre = preInstorageService.saveInstorageBillPre(preInstorageVo, billtype);
			
			logosticsInfo.setAboutCode(billPre.getBillCode());
			logosticsInfoDao.save(logosticsInfo);
			
			logger.info("退货入库成功");

			result.setFlag("success");
			result.setCode(QMErrorCode.SUCCESS.getCode());
			result.setMessage(QMErrorCode.SUCCESS.getMessage());
			result.setReturnOrderId(instorageBillPre.getBillCode().toString());
		}catch (ParseException e) {
			logger.info("保存错误",e);
			result.setMessage("failure");
			result.setCode(e.getMessage());
			result.setMessage("失败");
			result.setReturnOrderId("");
		}
		catch (Exception e) {
			logger.info("保存错误",e);
			
			result.setMessage("failure");
			result.setCode(e.getMessage());
			result.setMessage("失败");
			result.setReturnOrderId("");
		}
		StringWriter writer = new StringWriter();
		JAXB.marshal(result,writer);
		response.setResponseXml(writer.toString());
		return response;
	}

}
